﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace WebRole1
{
    public class TContext:TableServiceContext
    {
        public TContext(string baseaddress, StorageCredentials creds)
            : base(baseaddress, creds)
        { }

        //This function creates your table 
        private void createTable()
        {
            CloudStorageAccount
                .Parse(CloudConfigurationManager.GetSetting("MyConnectionString"))
                .CreateCloudTableClient().CreateTableIfNotExist("MyTableName");
        }

        //this function is for getting hte tabel service context 
        //rather than creating it in each function
        private TableServiceContext ServiceContext()
        {
            return CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("MyConnectionString"))
                .CreateCloudTableClient().GetDataServiceContext();

        }

        //adding a new user to the table
        public void addUser(string email, string name)
        {
            createTable();
            Entity e = new Entity(email) { name = name};
            var x = ServiceContext();
            x.AddObject("mytablename", e);
            x.SaveChangesWithRetries();
        }

        //getting a certain user from the table
        public Entity GetCertainUser(string parName, string email)
        {
            return (from e in ServiceContext().CreateQuery<Entity>("mytablename") 
                where e.PartitionKey == parName && e.RowKey == email
                select e).FirstOrDefault();
                                         
        }

        //getting all the users from a certain partition 
        // predefined whether by teh applciation or by the user
        public CloudTableQuery<Entity> GetAllUsers(string parName)
        {
            return (from e in ServiceContext().CreateQuery<Entity>("mytablename")
             where e.PartitionKey == parName 
             select e).AsTableServiceQuery();
        }
    }
}